import Player from '../Game/Player';
import { CharacterDir,CharacterState } from '../Tools/QType';
import ScriptManager from '../Tools/ScriptManager';
import QGame from '../Tools/QGame';
const {ccclass, property} = cc._decorator;

/**
 * 摇杆 
 */
@ccclass
export default class Rocket extends cc.Component {    
    private target:Player;

    private point:cc.Node;
    private _dir:CharacterDir;
    set dir(value){        
        if(this.dir==value)return;
        this._dir=value;   
        if(!this.target)return;
        if(this.dir===null){            
            this.target.state = CharacterState.Idle
        }else{            
            this.target.state = CharacterState.Move
            this.target.dir = this.dir;
        }
    }
    get dir(){
        return this._dir;
    }
    onLoad(){
        if(ScriptManager.Instance.Rocket)return;
        ScriptManager.Instance.Rocket=this;
        this.point = this.node.getChildByName("point");
        this.point.on(cc.Node.EventType.TOUCH_START,this.TouchStart,this);
        this.point.on(cc.Node.EventType.TOUCH_MOVE,this.TouchMove,this);
        this.point.on(cc.Node.EventType.TOUCH_END,this.TouchEnd,this);
        this.point.on(cc.Node.EventType.TOUCH_CANCEL,this.TouchEnd,this);
    }

    start(){
        
        let player = QGame.Instance.Team.getAt(0);
        if(player){
            this.target =player._node.getComponent(Player);
        }

    }

    setTarget(target:Player){
        this.target = target;    
    }

    TouchStart(event:cc.Event.EventTouch){        
        var p = this.node.convertToNodeSpaceAR(event.getLocation());        
        //计算p的方向    
        this.dir = this.getDirForAngle(p.signAngle(cc.Vec2.UP)*180/Math.PI)  
        this.point.position = p;     
    }
    TouchMove(event:cc.Event.EventTouch){
        var p = this.node.convertToNodeSpaceAR(event.getLocation());        
        if(p.mag()<(this.node.width-this.point.width)*0.6){
            this.dir =this.getDirForAngle(p.signAngle(cc.Vec2.UP)*180/Math.PI)  
            this.point.position = p;
        }        
    }
    TouchEnd(event:cc.Event.EventTouch){
        this.point.position = cc.Vec2.ZERO;
        this.dir = null;
    }

    /**
     * 根据角度获取方向
     */
    getDirForAngle(angle:number){        
        let dir:CharacterDir
        if( angle<45 && angle>=-45){
            dir = CharacterDir.Up
        }else if( angle<-45 && angle>=-135 ){            
            dir = CharacterDir.Left
        }else if( (angle<-135 && angle>=-180) || (angle>135 && angle<=180)  ){
            dir = CharacterDir.Down
        }else if( angle>45 && angle<=135 ){
            dir = CharacterDir.Right
        }
        
        return dir
    }
}
